/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.google.code.DB2SMS;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.BufferedImage;
import java.io.*;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ResourceBundle;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.plaf.metal.MetalIconFactory;

/**
 *
 * @author sgkezerlis
 */
public class FrameMain extends javax.swing.JFrame {

    public Timer timer;
    Connection con = null;
    Statement st = null;
    ResultSet rs = null;
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

    /**
     * Creates new form FrameMain
     */
    public FrameMain() {
        int seconds = Integer.valueOf(ResourceBundle.getBundle("Settings").getString("TIMER_INTERVAL"));
        initComponents();

        TrayIcon icon = new TrayIcon(Toolkit.getDefaultToolkit().getImage("ic_launcher.png"),
                "DB2SMSServer - gezerlis@gmail.com", createPopupMenu());
        setIconImage(Toolkit.getDefaultToolkit().getImage("ic_launcher.png"));
        icon.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                setVisible(!isVisible());
            }
        });
        icon.setImageAutoSize(true);

        try {
            SystemTray.getSystemTray().add(icon);
        } catch (AWTException ex) {
            Logger.getLogger(FrameMain.class.getName()).log(Level.SEVERE, null, ex);
        }

        addWindowListener(new WindowListener() {

            @Override
            public void windowIconified(WindowEvent arg0) {
                setVisible(!isVisible());
            }

            @Override
            public void windowOpened(WindowEvent e) {
            }

            @Override
            public void windowClosing(WindowEvent e) {
                System.out.println("windowClosing");
            }

            @Override
            public void windowClosed(WindowEvent e) {
                System.out.println("windowClosed");
            }

            @Override
            public void windowDeiconified(WindowEvent e) {
            }

            @Override
            public void windowActivated(WindowEvent e) {
                System.out.println("windowActivated");
            }

            @Override
            public void windowDeactivated(WindowEvent e) {
                System.out.println("windowDeactivated");
            }
        });

        timer = new Timer();
        timer.schedule(new RemindTask(), 0, seconds * 1000);

        Runtime rt = Runtime.getRuntime();
        try {
            String str = "";
            Process pr = rt.exec("adb get-serialno");
            DataInputStream ls_in = new DataInputStream(
                    pr.getInputStream());
            while ((str = ls_in.readLine()) != null) {
                System.out.println(str);
                lblDevice.setText("<html><b>USB Device SerialNo connected:</b> " + str);
                if (str.equals("unknown")) {
                    lblDevice.setText("<html><font color=red>No device connected!</font>");
                    //btnExit.doClick();
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(FrameMain.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private static Image getImage() throws HeadlessException {
        Icon defaultIcon = MetalIconFactory.getTreeHardDriveIcon();
        Image img = new BufferedImage(defaultIcon.getIconWidth(),
                defaultIcon.getIconHeight(),
                BufferedImage.TYPE_4BYTE_ABGR);
        defaultIcon.paintIcon(new Panel(), img.getGraphics(), 0, 0);
        return img;
    }

    private PopupMenu createPopupMenu() throws
            HeadlessException {
        PopupMenu menu = new PopupMenu();
        MenuItem hide = new MenuItem("Show/Hide");
        MenuItem log = new MenuItem("DB2SMSClient Log");
        MenuItem exit = new MenuItem("Exit");
        exit.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                btnExit.doClick();
            }
        });
        hide.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                setVisible(!isVisible());
            }
        });

        log.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                btnLog.doClick();
            }
        });
        menu.add(hide);
        menu.add(log);
        menu.add(exit);
        return menu;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnExit = new javax.swing.JButton();
        btnLog = new javax.swing.JButton();
        scrollReport = new javax.swing.JScrollPane();
        report = new javax.swing.JTextArea();
        lblDevice = new javax.swing.JLabel();

        setTitle("DB2SMSServer - gezerlis@gmail.com");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                MinimizeClose(evt);
            }
        });

        btnExit.setText("Exit");
        btnExit.setToolTipText("Exit G2SMS Server");
        btnExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExitActionPerformed(evt);
            }
        });

        btnLog.setText("DB2SMSClient Log File");
        btnLog.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLogActionPerformed(evt);
            }
        });

        report.setColumns(20);
        report.setEditable(false);
        report.setLineWrap(true);
        report.setRows(5);
        scrollReport.setViewportView(report);

        lblDevice.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblDevice.setText("Device:");
        lblDevice.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnLog)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblDevice, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnExit)
                .addContainerGap())
            .addComponent(scrollReport, javax.swing.GroupLayout.DEFAULT_SIZE, 559, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(scrollReport, javax.swing.GroupLayout.DEFAULT_SIZE, 193, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnExit)
                    .addComponent(btnLog)
                    .addComponent(lblDevice))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExitActionPerformed
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                setVisible(true);
                System.out.println("Exiting application");
                JOptionPane pane = new JOptionPane(
                        "Exit program?");
                Object[] options = new String[]{"Yes", "No"};
                pane.setOptions(options);
                JDialog dialog = pane.createDialog(new JFrame(), "EXIT");
                dialog.show();
                Object obj = pane.getValue();
                int result = -1;
                for (int k = 0; k < options.length; k++) {
                    if (options[k].equals(obj)) {
                        result = k;
                        if (result == 0) {
                            try {
                                String url = java.util.ResourceBundle.getBundle("Settings").getString("DB_URL");
                                String db = java.util.ResourceBundle.getBundle("Settings").getString("DB_DB");
                                String driver = java.util.ResourceBundle.getBundle("Settings").getString("DB_DRIVER");
                                String db_user = java.util.ResourceBundle.getBundle("Settings").getString("DB_USER");
                                String db_pass = java.util.ResourceBundle.getBundle("Settings").getString("DB_PASS");
                                con = null;
                                Class.forName(driver);
                                con = (Connection) DriverManager.getConnection(url + db + "?useUnicode=true&characterEncoding=UTF-8", db_user, db_pass);
                                Statement st = (Statement) con.createStatement();
                                String query = "set names utf8";
                                st.execute(query);
                                String sqlmo = "UPDATE module_available SET available='No' WHERE  module='ze_sms_send.php'";
                                st.executeUpdate(sqlmo);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            report.setText("Exiting program...");
                            System.exit(0);
                        } 
                    }
                }
            }
        });
    }//GEN-LAST:event_btnExitActionPerformed

    private void btnLogActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLogActionPerformed
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    Runtime rt = Runtime.getRuntime();
                    Process pr = rt.exec("adb pull /sdcard/db2sms/db2smsclient.log ./log.txt");
                    Desktop.getDesktop().open(new File("log.txt"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });


    }//GEN-LAST:event_btnLogActionPerformed

    private void MinimizeClose(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_MinimizeClose
        btnExit.doClick();
    }//GEN-LAST:event_MinimizeClose

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FrameMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrameMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrameMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrameMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new FrameMain().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnExit;
    private javax.swing.JButton btnLog;
    private javax.swing.JLabel lblDevice;
    public static javax.swing.JTextArea report;
    private javax.swing.JScrollPane scrollReport;
    // End of variables declaration//GEN-END:variables

    class RemindTask extends TimerTask {

        public void run() {
            String str = "";
            boolean dbcheck = true;
            Runtime rt = Runtime.getRuntime();
            String url = java.util.ResourceBundle.getBundle("Settings").getString("DB_URL");
            String db = java.util.ResourceBundle.getBundle("Settings").getString("DB_DB");
            String driver = java.util.ResourceBundle.getBundle("Settings").getString("DB_DRIVER");
            String db_user = java.util.ResourceBundle.getBundle("Settings").getString("DB_USER");
            String db_pass = java.util.ResourceBundle.getBundle("Settings").getString("DB_PASS");
            try {
                Process pr = rt.exec("adb get-serialno");
                DataInputStream ls_in = new DataInputStream(
                        pr.getInputStream());
                while ((str = ls_in.readLine()) != null) {
                    System.out.println(str);
                    lblDevice.setText("<html><b>USB Device SerialNo connected:</b> " + str);
                    if (str.equals("unknown")) {
                        lblDevice.setText("<html><font color=red>No device connected!</font>");
                        dbcheck = false;
                        try {
                            con = null;
                            Class.forName(driver);
                            con = (Connection) DriverManager.getConnection(url + db + "?useUnicode=true&characterEncoding=UTF-8", db_user, db_pass);
                            Statement st = (Statement) con.createStatement();
                            String query = "set names utf8";
                            st.execute(query);
                            String sqlmo = "UPDATE module_available SET available='No' WHERE  module='ze_sms_send.php'";
                            st.executeUpdate(sqlmo);
                        } catch (Exception e) {
                        }
                        //btnExit.doClick();
                    }
                }
                report.setText("");
                if (dbcheck) {
                    String fileName = "sms.txt";
                    report.setText(dateFormat.format(new Date()) + "\n\n" + "SCANNING DATABASE FOR PENDING SMS's\n");
                    // A File object to represent the filename
                    File f = new File(fileName);
                    if (f.exists()) {
                        f.delete();
                    }

                    con = null;
                    Class.forName(driver);
                    con = (Connection) DriverManager.getConnection(url + db + "?useUnicode=true&characterEncoding=UTF-8", db_user, db_pass);
                    Statement st = (Statement) con.createStatement();
                    String query = "set names utf8";
                    st.execute(query);
                    String sqlmo = "UPDATE module_available SET available='Yes' WHERE  module='ze_sms_send.php'";
                    //System.out.println(sql);
                    st.executeUpdate(sqlmo);
                    Statement stu = (Statement) con.createStatement();

                    String sql = "SELECT id,sms_recipient,sms_fault,sms_text "
                            + "FROM sms_to_client WHERE  email_sent='No'";
                    //System.out.println(sql);
                    rs = st.executeQuery(sql);
                    while (rs.next()) {
                        String phone = rs.getString("sms_recipient");
                        String message = rs.getString("sms_fault") + "-" + rs.getString("sms_text") + "-OTE";
                        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName, true), "UTF8"));

                        out.write(phone + "#" + message + "\n");
                        out.close();
                        report.append(phone + "#" + message + "\n");
                        String sqlu = "UPDATE sms_to_client SET email_sent='Yes' WHERE id=" + rs.getString("id");
                        stu.executeUpdate(sqlu);
                    }
                    pr = rt.exec("adb push sms.txt /sdcard/db2sms");

                    report.append("SCANNED DATABASE FOR PENDING SMS's\n\nNext scan in " + ResourceBundle.getBundle("Settings").getString("TIMER_INTERVAL") + "\"");
                    con.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
